package com.lyy.photovoltaic.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyy.photovoltaic.common.vo.ResultCode;
import com.lyy.photovoltaic.common.vo.ResultVO;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        //System.out.println(method);
        if ("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        String token = request.getHeader("token");//从请求头接收token

        System.out.println("------------"+token);
        if (token == null) {
            //提示请登录
            ResultVO resultVO = new ResultVO(ResultCode.NO, "请先登录", null);
            doResponse(response, resultVO);
        } else {
            try {
                //解析token
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("fasdfkjnior342f3");//与生成token时的密码一致
                //如果token正确（密码正确，有效期内） 则正常运行，否则抛出异常

                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;//可以放行
            } catch (ExpiredJwtException e) {
                ResultVO resultVO = new ResultVO(ResultCode.NO, "登录过期，请重新登录", null);
                doResponse(response, resultVO);
            } catch (UnsupportedJwtException e) {
                ResultVO resultVO = new ResultVO(ResultCode.NO, "token不合法", null);
                doResponse(response, resultVO);
            } catch (Exception e) {
                ResultVO resultVO = new ResultVO(ResultCode.NO, "请重新登录", null);
                doResponse(response, resultVO);
            }
        }
        return false;
    }


    //--------------------token只需要拦截器校验配置一次即可-------------------
//    //1.获取token
//    //2.检验token
//        if (token == null) {
//        return new ResultVO(ResultCode.FAILED, null);
//    } else {
//        try {
//            //解析token
//            JwtParser parser = Jwts.parser();
//            parser.setSigningKey("fasdfkjnior342f3");//与生成token时的密码一致
//            //如果token正确（密码正确，有效期内） 则正常运行，否则抛出异常
//
//            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
//
//            Claims body = claimsJws.getBody();  //获取token中的用户数据
//            String subject = body.getSubject();  //获取生成token设置的subject
//            String v1 = body.get("key1", String.class); //获取生成token时存储的map中的值
//
//            return resultVO;
//        } catch (ExpiredJwtException e) {
//            return new ResultVO(ResultCode.NO, "登录过期，请重新登录", null);
//        } catch (UnsupportedJwtException e) {
//            return new ResultVO(ResultCode.NO,"token不合法", null);
//        } catch (Exception e) {
//            return new ResultVO(ResultCode.NO, "登录过期，请重新登录", null);
//        }
    private void doResponse(HttpServletResponse response, ResultVO resultVO) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVO);
        out.print(s);
        out.flush();
        out.close();

    }
}
